/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helpdesk;

import java.sql.Timestamp;
import java.util.Date;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ChatServlet does two things. It sends the actual chat web page, and it sends
 * XML containing chat messages, errors, and users.
 *
 * To prevent the ChatServlet from sending every chat message ever made, it will
 * only send chat messages from the last 30 seconds. It has a parameter for the
 * id of the last chat message the client received so that messages are not sent
 * multiple times.
 *
 * ChatServlet keeps track of who is using the chat. It is very basic; it shows
 * all users that have submitted a message in the last 10 minutes.
 *
 * ChatServlet uses the following parameters for its XML interface:
 * 1) chat - Presence of the chat parameter indicates that this is an XML request.
 *    If missing, the chat page will be returned. Received via URL.
 * 2) lastId - Id number of the last message that was received by the client. If
 *    it is missing, all messages from the last 30 seconds will be returned. Should
 *    be in URL.
 * 3) message - Presence of a message field indicates that the user wants to
 *    submit a chat message. Should be post data.
 *
 * ChatServlet is dependent on the following session attributes:
 * 1) user - ChatServlet must know which user created the message
 *
 * ChatServlet produces XML of the following format:
 * <(xml header)>
 * <response>
 *  <statement> <- messages, can be multiple or none
 *   <id>unique id of chat statement</id>
 *   <userId>id of user that created statement</userId>
 *   <user>login name of the user (email)</user>
 *   <message>Contents of the message</message>
 *   <created>Date message was created</created>
 *  </statement>
 *  <chatter>email of users active in chat</chatter> <- may be none or multiple
 *  <error>Error text</error> <- should only be one
 * </response
 *
 * @author brian
 */
public class ChatServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String message;
        PrintWriter out = null;
        ArrayList<ChatStatement> chatStatements = null;
        User user;
        HttpSession session;

        
        try {

            if (request.getParameter("chat") != null) {
                try {
                    session = request.getSession();
                    int id=0;
                    long time;
                    time = new Date().getTime();
                    try
                    {
                        id = Integer.parseInt(request.getParameter("lastId"));
                    }
                    catch (Exception ex)
                    {
                        id = 0;
                    }
                    response.setContentType("text/xml;charset=UTF-8");
                    out=response.getWriter();
                    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                    out.println("<response>");
                    session = request.getSession();
                    if ((user=(User)request.getSession().getAttribute("user")) != null) {


                        if (request.getMethod().equals("POST") &&
                            (message = request.getParameter("message")) != null)
                        {
                            ChatStatement newStmt = new ChatStatement();
                            newStmt.setUserId(user.getId());
                            newStmt.setMessage(message);
                            newStmt.create();
                        }
                        // only get chat statements from last 30 seconds
                        chatStatements = ChatStatement.getChatStatements(id, new java.sql.Timestamp(time - 30000));
                        if (chatStatements != null && chatStatements.size() > 0) {
                            for (int i=0;i<chatStatements.size();i++)
                            {
                                ChatStatement stmt = chatStatements.get(i);
                                out.println(" <statement>");
                                out.println("  <id>" + stmt.getId() + "</id>");
                                out.println("  <userId>" + stmt.getUserId() + "</userId>");
                                out.println("  <user>" + stmt.getUser() + "</user>");
                                out.println("  <message>" + stmt.getMessage() + "</message>");
                                out.println("  <created>" + stmt.getCreated() + "</created>");
                                out.println(" </statement>");
                            
                            }
                        }
                        ArrayList <String> chatters = null;
                        chatters = ChatStatement.getRecentChatters(new Timestamp(time-600000));
                        if (chatters != null && chatters.size() > 0) {
                            for (int j=0;j<chatters.size();j++) {
                                out.println("<chatter>" + chatters.get(j) + "</chatter>");
                            }
                        }

                        out.println("</response>");
                    } else {
                        out.println(" <error>You are not logged in</error>");
                        out.println("</response>");
                    }
                    
                } catch (java.sql.SQLException e) {
                    out.println(" <error>SQL Exception: " + e.getMessage() + "</error>");
                    out.println("</response>");
                } catch (Exception ex) {
                    out.println(" <error>Exception: " + ex.getMessage());
                    ex.printStackTrace(out);
                    out.println("</error></response>");
                }
            } else {
                if (HelpdeskUtil.authenticateUser(request, response) != null) {
                    RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/chat.jsp");
                    rd.forward(request, response);
                }
            }
        } finally { 
            if (out != null) {
                out.close();
            }
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
